<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Validator, Storage;
use App\Models\Issue;
use App\Models\ArticleCat;
use App\Models\Article;

use Symfony\Component\HttpFoundation\File\UploadedFile;

class ApiController extends Controller
{

	const JOURNAL_ID = 1;
	public function post(Request $request)
	{
		if ($request->isMethod('post')) {

		}

		// $input = $request->input('foo');
		// $request->validate([
		// 	'body' => 'required'
		// ]);
		$input = $request->all();

		$validator = Validator::make($input, [
		    'journal_name' => 'required',
			'article_id' => 'required',
			'doi' => 'required',
			// 'subject' => 'required',
			'title' => 'required',
			'author' => 'required',
			// 'corresponding_email' => 'required',
			// 'affiliation' => 'required',
			// 'pub_date' => 'required',
			'volume' => 'required',
			'issue' => 'required',
			'page_start' => 'required',
			'page_end' => 'required',
			// 'received_date' => 'required',
			// 'accepted_date' => 'required',
			// 'abstract' => 'required',
			// 'keywords' => 'required',
			// 'founding' => 'required',
			'xml' => 'required|mimes:xml'
			// 'pdf' => 'required|mimes:pdf'
		]);

		if ($validator->fails()) {
			$errors = $validator->errors();

			return response()->json($errors->all());
		}

		$journalId = self::JOURNAL_ID;
		try {
			$issue = Issue::where('year', date('Y'))
				->where('volume', $input['volume'])	
				->where('issue', $input['issue'])
				->first();

			if (!$issue) {
				$issue = new Issue;
				$issue->journal_id = $journalId;
				$issue->title = $issue->title_en = date('Y') .  'Vol.' . $input['volume'] . ' No.' . $input['issue'] . ' ' . date('Y-m-d');
				$issue->year = date('Y');
				$issue->volume = $input['volume'];
				$issue->issue = $input['issue'];
				$issue->page_start = 0;
				$issue->page_end = 0;
				$issue->save();
			}

			$subjectId = ArticleCat::ARTICLE_ID;
			if (isset($input['subject']) && $input['subject']) {
				$subject = ArticleCat::where('name', $input['subject'])->first();
				if ($subject) {
					$subjectId = $subject->id;
				}
			}

			$xml = null;
			if (isset($input['xml'])) {
				if (Storage::disk('admin')->putFileAs('files', $input['xml'], $input['article_id'] . '.xml')) {
					$xml = 'files/' . $input['article_id'] . '.xml';
				}
			}

			$pdf = null;
			if (isset($input['pdf'])) {
				if (Storage::disk('admin')->putFileAs('files', $input['pdf'], $input['article_id'] . '.pdf')) {
					$pdf = 'files/' . $input['article_id'] . '.pdf';
				}
			}

			$imgs = [];
			if (isset($input['pics']) && count($input['pics']) > 0) {
				foreach ($input['pics'] as $pic) {
					if ($pic instanceOf UploadedFile) {
						$uName = $this->generateUniqueName($pic);

						if (Storage::disk('admin')->putFileAs('images', $pic, $uName)) {
							$imgs[] = 'images/' . $uName;
						}
					}
				}
			}



			
			$iArr = array(
				'journal_id' => $journalId,
				'issue_id' => $issue->id,
				'cate_id' => $subjectId,
				'page_start' => $input['page_start'],
				'page_end' => $input['page_end'],
				// 'cite_count' => '',
				'title' => $input['title'],
				'id_doi' => $input['doi'],
				'author_list' => $input['author'],
				'affiliation' => isset($input['affiliation']) ? $input['affiliation'] : '',
				'corresponding_info' => isset($input['corresponding_email']) ? $input['corresponding_email'] : '',
				'abstract' => isset($input['abstract']) ? $input['abstract'] : '',
				'keywords' => isset($input['keywords']) ? $input['keywords'] : '',
				'fund' => isset($input['founding']) ? $input['founding'] : '',
				'accept_date' => isset($input['accepted_date']) ? $input['accepted_date'] : null,
				'revision_date' => isset($input['received_date']) ? $input['received_date'] : null,
				'publish_date' => isset($input['pub_date']) ? $input['pub_date'] : date('Y-m-d H:i:s'),
				'xml_id' => $input['article_id'],
				'xml' => $xml,
				'pdf' => $pdf,
				'imgs' => $imgs
			);

			$article = Article::where('xml_id', $input['article_id'])->first();

			if ($article) { //delete original files
				if ($article->xml != $iArr['xml']) {
					Storage::disk('admin')->delete($article->xml);
				}
				if ($article->pdf != $iArr['pdf']) {
					Storage::disk('admin')->delete($article->pdf);
				}
				if ($article->imgs) {
					Storage::disk('admin')->delete($article->imgs);
				}
			}

			$article = Article::updateOrCreate(['xml_id' => $input['article_id']], $iArr);
			return response()->json([
				'status_code' => 200,
				'url' => route('article.index', ['id' => $article->id]),
				'message' => 'Upload article ' . $input['article_id'] . ' done.' 
			]);
		} catch(\Exception $e) {
			return response()->json([
				'status_code' => 404,
				'message' => $e->getMessage()
			]);
		}
	}


	private function generateUniqueName(UploadedFile $file)
    {
        return md5(uniqid()).'.'.$file->getClientOriginalExtension();
    }
}